/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.meteocal.control;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import net.aksingh.java.api.owm.DailyForecastData;

/**
 *
 * @author paolo
 */
@Singleton
public class WeatherService {

    @PersistenceContext
    private EntityManager em;
    @EJB
    private ForecastManager fm;

    /**
     * scheduled method that update all the forecast every day at this our:
     * 2:1,5:1,8:1,11:1,17:1,18:1,19:1,20:1,23:1 ten days in the future of
     * forecast are available
     */
    @Schedule(dayOfWeek = "*", hour = "2,5,8,11,17,18,19,20,23", minute = "1")
    public void retrieveCityToUpdate() {
        System.out.println("**********UPDATE FORECAST********");
        /*
         TypedQuery<String> cityToUpdateQuery = em.createQuery("SELECT f.city FROM Forecast f WHERE f.forecastDate >= :dateF GROUP BY f.city", String.class);
         GregorianCalendar dateF = new GregorianCalendar();
         cityToUpdateQuery.setParameter("dateF", dateF);
         List<String> cityToUpdate = cityToUpdateQuery.getResultList();
         */
        GregorianCalendar dateS = new GregorianCalendar();
        GregorianCalendar dateF = new GregorianCalendar();
        dateF.add(Calendar.DAY_OF_YEAR, 10);
        String query = "SELECT f.city FROM Forecast f WHERE (f.forecastDate BETWEEN " + "'" + dateS.get(Calendar.YEAR) + "-" + (dateS.get(Calendar.MONTH) + 1) + "-" + dateS.get(Calendar.DAY_OF_MONTH) + "'" + " AND " + "'" + dateF.get(Calendar.YEAR) + "-" + (dateF.get(Calendar.MONTH) + 1) + "-" + dateF.get(Calendar.DAY_OF_MONTH) + "'" + ") GROUP BY f.city";
        System.out.println("QUERY: " + query);
        TypedQuery<String> cityToUpdateQuery = em.createQuery(query, String.class);
        List<String> cityToUpdate = cityToUpdateQuery.getResultList();
        for (String city : cityToUpdate) {
            System.out.println(city);
        }
        for (String city : cityToUpdate) {
            System.out.println("-----city to update: " + city);
            List<DailyForecastData.Forecast> cityForecast = fm.getCityForecast(city);
            if (cityForecast == null) {
                System.out.println("-----no forecast");
            } else {
                fm.updateForecast(city, cityForecast);
            }
        }
    }
}
